package main

import (
	"fmt"
	"net/http"

	"gitee.com/Gakusyun/gakusyun-ws/admin"
	"gitee.com/Gakusyun/gakusyun-ws/cli"
	"gitee.com/Gakusyun/gakusyun-ws/config"
	"gitee.com/Gakusyun/gakusyun-ws/logging"
	"gitee.com/Gakusyun/gakusyun-ws/server"
	"gitee.com/Gakusyun/gakusyun-ws/utils"
	"gitee.com/Gakusyun/gakusyun-ws/version"
)

func main() {
	// 解析命令行参数
	args := cli.ParseArgs()

	// 执行相应的动作，如果不需要运行服务器则直接退出
	if !cli.ExecuteAction(args) {
		return
	}

	// 正常启动服务器
	fmt.Println("GSWS is running!")
	fmt.Printf("Version: %s\n", version.GetVersion())

	// 初始化日志记录器
	logger, err := logging.NewLogger()
	if err != nil {
		fmt.Printf("Failed to initialize logger: %v\n", err)
		return
	}
	defer logger.Close()

	// 读取配置
	cfg, err := config.ReadConfig(logger.Logger)
	if err != nil {
		logger.Fatalf("Failed to read config: %v", err)
	}

	// 验证配置
	if err := config.ValidateConfig(cfg); err != nil {
		logger.Fatalf("Invalid configuration: %v", err)
	}

	// 初始化统计信息
	stats := utils.NewServerStats()

	// 创建静态文件服务器
	fileServer := server.NewStaticFileServer(&cfg, stats, logger.Logger)

	// 创建管理界面处理器
	adminHandler := admin.NewAdminHandler(stats, logger.Logger)

	// 设置路由 - 使用开发者拦截器中间件
	http.HandleFunc("/", server.DevInterceptorMiddleware(&cfg, fileServer.ServeFile))
	http.HandleFunc("/gsws-about", server.DevInterceptorMiddleware(&cfg, adminHandler.AboutHandler))
	http.HandleFunc("/gsws-stats", server.DevInterceptorMiddleware(&cfg, adminHandler.StatsHandler))

	// 启动日志归档
	archiver := logging.NewArchiver(logger.Logger)
	archiver.StartDailyArchiving()
	archiver.StartMonthlyArchiving()

	// 启动服务器
	addr := cfg.Host + ":" + cfg.Port
	logger.Printf("Server started on http://%s", addr)

	fmt.Printf("Server started on http://%s\n", addr)

	fmt.Printf("Admin pages:\n")
	fmt.Printf("  - About: http://%s/gsws-about\n", addr)
	fmt.Printf("  - Stats: http://%s/gsws-stats\n", addr)

	logger.Fatal(http.ListenAndServe(addr, nil))
}
